package web.security.service;

import module.model.SysRoleModel;
import module.model.UserModel;
import module.service.SysRoleService;
import module.service.UserService;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import web.security.vo.UserDetailVo;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;


public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private UserService userService;
    @Autowired
    private SysRoleService sysRoleService;

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserModel sysUser = userService.findByAdminLoginId(username);
        if (sysUser == null) {
            throw new UsernameNotFoundException("管理员[" + username + "]不存在!");
        }
        UserDetailVo userDetailVo = new UserDetailVo();
        userDetailVo.setUsername(username);
        userDetailVo.setPassword(sysUser.getUserPassword());
        userDetailVo.setAuthorities(getUserGrantedAuthority(sysUser));
        return userDetailVo;
    }

    private List<SimpleGrantedAuthority> getUserGrantedAuthority(UserModel userModel){
        List<SimpleGrantedAuthority> simpleGrantedAuthorityList = new ArrayList<SimpleGrantedAuthority>();
        List<SysRoleModel> sysRoleList = sysRoleService.findSysUserRole(userModel.getUserId());
        for(SysRoleModel sysRole : sysRoleList){
            simpleGrantedAuthorityList.add(new SimpleGrantedAuthority(sysRole.getRoleValue()));
        }
        return simpleGrantedAuthorityList;
    }
}
